package com.xfcy.blog.utils;

import cn.hutool.core.bean.BeanUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 晓风残月Lx
 * @date 2023/4/18 17:59
 */
public class BeanCopyUtil {

    /**
     * copy 集合
     * @param sourceList
     * @param clazz
     * @return
     * @param <T1>
     * @param <T2>
     */
    public static <T1, T2> List<T2> listCopy(List<T1> sourceList, Class<T2> clazz) {
        return (List) sourceList.stream().map((item) -> {
            Object target;

            try {
                target = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            BeanUtil.copyProperties(item, target);
            return target;
        }).collect(Collectors.toList());
    }

    /**
     * 复制对象
     * @param source
     * @param target
     * @return
     * @param <T>
     */
    public static <T> T copyObject(Object source, Class<T> target) {
        T temp = null;
        try {
            temp = target.newInstance();
            if (null != source) {
                org.springframework.beans.BeanUtils.copyProperties(source, temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }
}
